from flask import current_app
from flask import redirect
from flask import render_template
from flask import request
from flask import session
from flask import url_for

from info.models import User
from . import admin_blu


@admin_blu.route('/login', methods=["GET", "POST"])
def login():
    if request.method == 'GET':
        user_id = session.get('user_id', None)
        is_admin = session.get('is_admin', False)
        # 判断是否已经是管理员登录
        if user_id and is_admin:
            return redirect(url_for('admin.index'))
        return render_template("admin/login.html")

    # 1、获取参数判空
    username = request.form.get("username")
    password = request.form.get("password")
    if not all([username, password]):
        return render_template('admin/login.html', errmsg = "参数不足")

    # 2、查询数据库， 看是否有该用户
    try:
        user = User.query.filter(User.mobile == username).first()
    except Exception as e:
        current_app.logger.error(e)
        return render_template('admin/login.html', errmsg = "数据查询失败")

    if not user:
        return render_template('admin/login.html', errmsg = "用户不存在")

    # 3、校验密码是否正确
    if not user.check_passowrd(password):
        return render_template('admin/login.html', errmsg = "密码错误")

    # 4、校验是否是管理员
    if not user.is_admin:
        return render_template('admin/login.html', errmsg = "用户权限错误")

    # 5、保存用户登陆信息到session
    session['user_id'] = user.id
    session['nick_name'] = user.nick_name
    session['mobile'] = user.mobile
    session['is_admin'] = True

    # 6、登录成功重定向到管理员首页
    return render_template('admin/index.html')

